package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.ExcelSubject;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Miluo
 * @description Excel导入监听器
 **/
@Slf4j
public class ExcelSubjectListener extends AnalysisEventListener<ExcelSubject> {

    private SubjectMapper subjectMapper;

    public ExcelSubjectListener(SubjectMapper subjectMapper){
        this.subjectMapper = subjectMapper;
    }


    //查询一级标题是否存在
    private Subject getOneLevelTitle(String title){
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id","0");
        Subject subject = subjectMapper.selectOne(queryWrapper);
        return subject;
    }

    //查询二级分类是否存在
    private Subject getTwoLevelTitle(String title,String parentId){
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id",parentId);
        Subject subject = subjectMapper.selectOne(queryWrapper);
        return subject;
    }



    @Override
    public void invoke(ExcelSubject excelSubject, AnalysisContext analysisContext) {
        log.info("解析到一条记录: {}", excelSubject);
        String oneLevelTile = excelSubject.getOneLevelTitle();
        String twoLevelTile = excelSubject.getTwoLevelTitle();
        System.out.println(oneLevelTile);
        System.out.println("111111");

        Subject oneLevelTitleSubject = this.getOneLevelTitle(oneLevelTile);
        String parentId = null;
        if (oneLevelTitleSubject == null){

            Subject subject = new Subject();
            subject.setTitle(oneLevelTile);
            subject.setParentId("0");
            subjectMapper.insert(subject);
            parentId = subject.getId();
        }else{
            parentId = oneLevelTitleSubject.getId();
        }



        Subject twoLevelTitleSubject = this.getTwoLevelTitle(twoLevelTile, parentId);
        if (twoLevelTitleSubject == null){
            Subject subject = new Subject();
            subject.setTitle(twoLevelTile);
            subject.setParentId(parentId);
            subjectMapper.insert(subject);
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
